package com.shimao.celnet.payment.controller.api;

import com.shimao.celnet.payment.common.exception.BaseException;
import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.model.PPayDetail;
import com.shimao.celnet.payment.model.request.CallIn_OutPayReqInRequest;
import com.shimao.celnet.payment.model.request.Payment;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.BEstateService;
import com.shimao.celnet.payment.service.BHouseService;
import com.shimao.celnet.payment.service.PPayBusinessService;
import com.shimao.celnet.payment.service.PPayService;
import com.shimao.celnet.payment.util.FinalUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 外部系统 → 支付系统，数据：付款申请账单
 * 外部系统通过本接口返回的【paymentId】，访问支付平台统一的【支付方式选择】页面，
 * 2017/12/14
 * christ
 */
@RestController
@RequestMapping("/payment")
@Api("接口：pay-140-外部付款申请<outPayReqIn> 外部系统 → 支付系统，数据：付款申请账单")
public class CallIn_outPayReqInController {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired//支付申请
    private PPayService pPayService;

    @Autowired//房间
    private BHouseService bHouseService;

    @Autowired//小区
    private BEstateService bEstateService;

    @Autowired
    private PPayBusinessService pPayBusinessService;

    /**
     * 外部系统支付申请
     *
     * @param requestJson
     * @throws BaseException
     */
    @ApiOperation("获取外部请求付款数据")
    @RequestMapping(value = "/payReq", method = RequestMethod.POST)
    public String OutPayReqInController(@RequestBody @Valid CallIn_OutPayReqInRequest requestJson, BindingResult result) throws IOException, ParseException, BaseException {
        logger.info("pay-140-外部付款申请<outPayReqIn>请求JSON:" + requestJson.toString());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        //界面输入验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                logger.debug("缺少必要参数：" + error.getDefaultMessage());
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson.toString();
            }
        }
        PPay pPay = new PPay();
        String payGuid = pPayService.getGuid();
        pPay.setGuid(payGuid);
        pPay.setCreatedUserGuid(FinalUtil.INTER_FACE_USER_ID);
        pPay.setUpdateUserGuid(FinalUtil.INTER_FACE_USER_ID);
        pPay.setBusinessType(requestJson.getpOrderType());    //	业务类型
        //处理一下传入金额，按长整型处理,以分为单位，不处理小数位
        Long money = new Double(requestJson.getpMoney()).longValue();
        pPay.setPayAmount(money.toString());    //	支付金额
        pPay.setPayStartTime(String.valueOf(System.currentTimeMillis()));//	支付开始时间
        if(requestJson.getEstateId() != null && requestJson.getEstateId()!= ""){
            if(bEstateService.getBySfGuid(requestJson.getEstateId()) != null){
                pPay.setEstateGuid(bEstateService.getBySfGuid(requestJson.getEstateId()).getGuid());    //	小区guid
                pPay.setEstateSfGuid(requestJson.getEstateId());    //	小区SF-GUID
            }else {
                pPay.setEstateGuid(pPayBusinessService.getByGuid(requestJson.getEstateId()).getGuid());
                pPay.setEstateSfGuid(requestJson.getEstateId());    //	小区SF-GUID
            }
        }
        if(requestJson.getHouseId() != null && requestJson.getHouseId()!= ""){
            if(requestJson.getEstateId() == "" || requestJson.getEstateId() == null){
                pPay.setEstateGuid(bHouseService.getBySfGuid(requestJson.getHouseId()).getEstateGuid());
            }
            pPay.setHourceGuid(bHouseService.getBySfGuid(requestJson.getHouseId()).getGuid());    //	支付房间guid
        }
        pPay.setHourceSfGuid(requestJson.getHouseId());    //	支付房间SF-GUID
        pPay.setPayUserSfGuid(requestJson.getUserId());    //	支付用户SF-GUID
        pPay.setPayUserName(requestJson.getUserName());    //	支付用户名称
        pPay.setPayRemark(requestJson.getpRemark());       //	支付说明
        pPay.setGoBackUrl(requestJson.getGoBackUrl());     //   支付成功回调url
        pPay.setPayAppType(requestJson.getpAppType());     //   app类型
        pPay.setPayAppName(requestJson.getpAppName());     //   APP名字
        pPay.setPayAppPackage(requestJson.getpAppPackage());//  APP包
        pPay.setPayCusip(requestJson.getpCusip());         //   终端ip
        pPay.setAcct(requestJson.getAcct());//微信小程序-小程序的openid（小程序支付必填）
        pPay.setSub_appid(requestJson.getSub_appid()); //   微信小程序的appid（小程序支付必填
        pPay.setAppKey(request.getHeader(FinalUtil.HEADER_APP_KEY));//app_key
        pPay.setInterfaceId(request.getHeader(FinalUtil.HEADER_INTERFACE_ID));//接口id
        List<Payment> paymentList = requestJson.getPaymentList();
        List<PPayDetail> pPayDetailList = new ArrayList<PPayDetail>();
        for (Payment payment : paymentList) {
            PPayDetail pPayDetail = new PPayDetail();
            pPayDetail.setExsysDetailId(payment.getReceivableId());//外部系统明细id
            pPayDetail.setAmount(payment.getTotalReceivableAmount());//明细金额
            pPayDetail.setRemark(payment.getbRemark());//明细说明
            //支付申请记录明细保存
            pPayDetailList.add(pPayDetail);
        }
        //支付申请记录保存
        pPayService.save(pPay,pPayDetailList);
        retJson.addBody("paymentId", payGuid);//返回订单的guid
        return retJson.toString();
    }


}
